<template>
  <ul class="list">
    <li class="item" v-for="item in letters" :key="item" :ref="item" @click="handleLetterClick" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd">{{item}}</li>
  </ul>
</template>

<script>
export default {
  name: 'cityalphabet',
  props: {
    cities: Object
  },
  data() {
    return {
      touchStatus: false,
      startY: 0,
      timer: null
    }
  },
  computed: {
    letters() {
      const letters = []
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
      //    letters:['A','B']
    }
  },
  updated() {
    this.startY = this.$refs['A'][0].offsetTop
  },
  methods: {
    handleLetterClick(event) {
      // console.log(event.target.innerText)
      this.$emit('change', event.target.innerText)
      //  事件订阅的一种，父在引用的子组件上绑方法，子通过同名，change调用，传过来letter
      //  on emit 水杯发水绑定，水发送水触发
    },
    handleTouchStart() {
      this.touchstatus = true
    },
    handleTouchMove(e) {
      if (this.touchstatus) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        //                                                 const startY = this.$refs['A'][0].offsetTop
        //                                                 // A这个元素0项真正的dom元素距离顶部的高度 offsetTop clientY分别
        //                                                 // console.log(startY)
        //                                                 const touchY = e.touches[0].clientY - 79
        //                                                 // console.log(touchY)
        //                                                 // event事件对象里面的会有一个touches的数组 0项位手指的位置信息
        //                                                 const index = Math.floor((touchY - startY) / 20)
        //                                                 // console.log(index)
        //                                                 if (index >= 0 && index < this.letters.length) {
        //                                                   this.$emit('change', this.letters[index])
        //                                                   // 字母表传给city,city改变letter值，传给list，区域变动
        // }
        this.timer = setTimeout(() => {
          const touchY = e.touches[0].clientY - 79
          const index = Math.floor((touchY - this.startY) / 20)
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        }, 16)
      }
    },
    handleTouchEnd() {
      this.touchstatus = false
    }
  }
}
</script>

<style scoped>
.list {
  display: flex;
  flex-direction: column;
  justify-content: center;
  position: absolute;
  right: 0;
  top: 1.58rem;
  bottom: 0;
  width: 0.4rem;
}
.item {
  text-align: center;
  line-height: 0.44rem;
  color: #00bcd4;
}
</style>